package com.fengjue.mail;

import com.fengjue.common.utils.JedisUtil;
import com.fengjue.pojo.Employee;
import com.fengjue.pojo.MailConstants;
import com.rabbitmq.client.Channel;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import redis.clients.jedis.Jedis;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.xml.transform.Templates;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class MailReceiver {

    private static final Logger log = LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;




//    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
//    public void listener(Employee employee){
//        MimeMessage msg = javaMailSender.createMimeMessage();
//        MimeMessageHelper helper = new MimeMessageHelper(msg);
//
//        try {
//
//            //=======================设置邮件=======================
//            // 设置发件人
//            helper.setFrom(mailProperties.getUsername());
//            // 设置收件人
//            helper.setTo(employee.getEmail());
//            // 设置邮件主标题
//            helper.setSubject("入职欢迎邮件");
//            // 邮件发送日期
//            helper.setSentDate(new Date());
//
//
//            //=======================设置邮件内容=======================
//            Context context = new Context();
//            Map<String,Object> map = new HashMap<>();
//            map.put("name",employee.getName());
//            map.put("posName",employee.getPosition().getName());
//            map.put("joblevelName",employee.getJoblevel().getName());
//            map.put("departmentName",employee.getDepartment().getName());
//            context.setVariables(map);
//
//            // 指向mail.html
//            String mail = templateEngine.process("mail", context);
//            helper.setText(mail,true);
//
//
//            //=======================发送邮件=======================
//            javaMailSender.send(msg);
//
//            log.info("邮件发送成功");
//
//        } catch (MessagingException e) {
//            log.error("邮件发送失败,{}",e.getMessage());
//        }
//
//
//    }



    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void listener(Message message, Channel channel){
        Jedis jedis = JedisUtil.getInstance().getPool().getResource();
        Employee employee = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        // 消息序号
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String) headers.get("spring_returned_message_correlation");








        try {

            if(jedis.get("mail_log").equals(msgId)){
                log.error("该消息已经被消费，id为{}",msgId);
                /**
                 * 手动确认消息
                 */
                channel.basicAck(tag,false);
                return;
            }



            MimeMessage msg = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg);

            //=======================设置邮件=======================
            // 设置发件人
            helper.setFrom(mailProperties.getUsername());
            // 设置收件人
            helper.setTo(employee.getEmail());
            // 设置邮件主标题
            helper.setSubject("入职欢迎邮件");
            // 邮件发送日期
            helper.setSentDate(new Date());


            //=======================设置邮件内容=======================
            Context context = new Context();
            Map<String,Object> map = new HashMap<>();
            map.put("name",employee.getName());
            map.put("posName",employee.getPosition().getName());
            map.put("joblevelName",employee.getJoblevel().getName());
            map.put("departmentName",employee.getDepartment().getName());
            context.setVariables(map);

            // 指向mail.html
            String mail = templateEngine.process("mail", context);
            helper.setText(mail,true);


            //=======================发送邮件=======================
            javaMailSender.send(msg);

            log.info("邮件发送成功");
            // 将消息id存入redis
            jedis.set("mail_log",msgId);
            // 手动确认消息
            channel.basicAck(tag,false);
            jedis.close();
        } catch (Exception e) {
            /**
             * 手动确认消息
             * channel.basicNack(tag,false,true);
             *                  消息序号，是否确认多条，是否退回到队列
             */
            try {
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                log.error("邮件发送失败,{}",ex.getMessage());
            }
            log.error("邮件发送失败,{}",e.getMessage());
        }


    }


}
